<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height: 60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="hAdd"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <el-table :data="roles">
              <el-table-column label="序号" width="120">
                <template v-slot="data">{{
                  data.$index + 1 + q.page * q.pagesize - q.pagesize
                }}</template>
              </el-table-column>
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="small"
                    type="success"
                    @click="hAssign(scope.row.id)"
                  >分配权限</el-button>
                  <el-button
                    size="small"
                    type="primary"
                    @click="hEdit(scope.row)"
                  >编辑</el-button>
                  <el-button
                    size="small"
                    type="danger"
                    @click="delhandleCurrentChange(scope.row.id)"
                  >删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <el-row
              type="flex"
              justify="center"
              align="middle"
              style="height: 60px"
            >
              <!-- 分页组件 -->
              <el-pagination
                :current-page="q.page"
                :page-sizes="[1, 2, 3, 4]"
                :page-size="q.pagesize"
                layout="total, sizes, prev, pager, next"
                :total="total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
    </div>

    <!-- 新增弹框 -->
    <el-dialog
      :title="flag ? '编辑' : '添加'"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialog"
      @close="resetForm"
    >
      <el-form
        ref="roleForm"
        :rules="rulesForm"
        :model="roleForm"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="showDialog = false">取消</el-button>
          <el-button
            size="small"
            type="primary"
            @click="hSubmit"
          >确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 新增弹框 -->
    <el-dialog
      title="分配权限"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogAssign"
    >
      <assign-permission
        v-if="showDialogAssign"
        :cur-id="curId"
        @success="success"
      />
    </el-dialog>
  </div>
</template>

<script>
import { getRoles, delRoles, addRole, updateRole } from '@/api/setting'
import assignPermission from './assignPermission'
export default {
  components: { assignPermission },
  data() {
    return {
      // 父传子id
      curId: '',
      // 角色信息列表
      roles: [],
      // 角色信息一页总条数
      total: 0,
      // 分页数据
      q: {
        page: 1,
        pagesize: 1
      },
      // 显示弹窗
      showDialog: false,
      // 显示分配权限弹窗
      showDialogAssign: false,
      // 弹窗表单数据
      roleForm: {
        name: '',
        description: ''
      },
      // 分别编辑 和 添加的弹框
      flag: false,
      // 表单校验规则
      rulesForm: {
        name: [
          { required: true, message: '角色名称不能为空！', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空！', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadRoles(this.q)
  },
  methods: {
    // 子组件确认关闭权限弹窗
    success() {
      this.showDialogAssign = false
    },
    // 点击弹窗分配权限
    hAssign(id) {
      this.showDialogAssign = true
      this.curId = id
    },
    // 获取所有角色信息
    async loadRoles(q) {
      try {
        const res = await getRoles(q)
        // console.log(res)
        this.roles = res.data.rows
        this.total = res.data.total
        // console.log(this.total)
      } catch (err) {
        this.$message.warning(err)
      }
    },
    // 每页的条数
    handleSizeChange(val) {
      //   console.log(`每页 ${val} 条`)
      this.q.pagesize = val
      this.q.page = 1
      this.loadRoles(this.q)
    },
    // 当前页码
    handleCurrentChange(val) {
      //   console.log(`当前页: ${val}`)
      this.q.page = val
      this.loadRoles(this.q)
    },
    // 删除当前角色
    delhandleCurrentChange(id) {
      this.$confirm('此操作将永久的删除本数据，确认继续吗', '提示', {
        type: 'warning',
        cancelButtonText: '取消',
        confirmButtonText: '确认'
      })
        .then(async() => {
          try {
            const res = await delRoles(id)
            this.$message.success(res.message)
            // 如果一页的数据等于1 并且 页码不等于 1 ，就把页面加一并渲染页面
            if (this.roles.length === 1 && this.q.page !== 1) {
              this.q.page--
            }
            this.loadRoles(this.q)
          } catch (error) {
            this.$message.warning(error)
          }
        })
        .catch(() => {})
    },
    // 点击确认提交
    hSubmit() {
      this.$refs.roleForm.validate(async(valid) => {
        if (!valid) return
        this.flag ? this.doEdit() : this.doAdd()
      })
    },
    // 添加
    async doAdd() {
      try {
        const res = await addRole(this.roleForm)
        this.$message.success(res.message)
        this.showDialog = false
        // 点击添加跳转到最后一页，显示新添加的数据
        // 先将总条数加一，可以让最后
        this.total++
        this.q.page = Math.ceil(this.total / this.q.pagesize)
        this.loadRoles(this.q)
        this.flag = false
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑
    async doEdit() {
      try {
        const res = await updateRole(this.roleForm)
        this.$message.success(res.message)
        this.showDialog = false
        this.loadRoles(this.q)
      } catch (error) {
        console.log(error)
      }
    },
    // 编辑弹窗
    hEdit(row) {
      this.showDialog = true
      this.flag = true
      // 数据回填， 与表单数据深拷贝
      this.roleForm = { ...row }
    },
    // 添加弹窗
    hAdd() {
      this.showDialog = true
      this.flag = false
    },
    // 关闭弹框重置表单
    resetForm() {
      this.$refs.roleForm.resetFields()
    }
  }
}
</script>
